﻿using System;
using Microsoft.Win32;

class Registry_Add
{
    // 在 HKEY_CLASSES_ROOT 下注册右键菜单（背景/目录）
    // HKEY_CLASSES_ROOT\Directory\Background\shell
    // HKEY_CLASSES_ROOT\Directory\shell
    public static int AddAppShellKeys(string appName)
    {
        string[] paths =
        {
            $@"Directory\Background\shell\{appName}",
            $@"Directory\shell\{appName}"
        };
        return Add_Classes_RootKeys(appName, paths);
    }

    private static int Add_Classes_RootKeys(string appName, params string[] paths)
    {
        int addedCount = 0;

        foreach (var path in paths)
        {
            try
            {
                string parentPath = System.IO.Path.GetDirectoryName(path);
                string subKeyName = System.IO.Path.GetFileName(path);

                using (RegistryKey parentKey = Registry.ClassesRoot.OpenSubKey(parentPath, writable: true))
                {
                    if (parentKey == null)
                    {
                        Console.WriteLine($"未找到父路径: {parentPath}");
                        continue;
                    }

                    using (RegistryKey targetKey = parentKey.CreateSubKey(subKeyName))
                    {
                        if (targetKey == null)
                        {
                            Console.WriteLine($"创建子键失败: {path}");
                        }
                        else
                        {
                            // 可以在这里写入默认值或者命令，比如打开记事本
                            targetKey.SetValue("", $"右键菜单: {appName}");
                            // 示例：设置一个默认命令（右键点击时执行）
                            using (RegistryKey commandKey = targetKey.CreateSubKey("command"))
                            {
                                commandKey.SetValue("", @"notepad.exe"); // 默认打开记事本
                            }

                            Console.WriteLine($"已添加注册表项: {path}");
                            addedCount++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加 {path} 失败: {ex.Message}");
            }
        }

        return addedCount;
    }
}

class Add
{
    public static void Run()
    {
        string appName = "QQ";
        int result = Registry_Add.AddAppShellKeys(appName);

        Console.WriteLine($"注册完成，共添加 {result} 个注册表项。");
    }
}
